package com.like.miaosha.service;

import com.like.miaosha.domain.MiaoshaOrder;
import com.like.miaosha.domain.MiaoshaUser;
import com.like.miaosha.domain.OrderInfo;
import com.like.miaosha.rebbitmq.MiaoshaMessage;
import com.like.miaosha.redis.MiaoshaKey;
import com.like.miaosha.redis.RedisService;
import com.like.miaosha.util.MD5Util;
import com.like.miaosha.util.UUIDUtil;
import com.like.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Service
public class MiaoshaService {
    @Autowired
    OrderService orderService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    RedisService redisService;
    private void setGoodsOver(Long goodsId) {
        redisService.set(MiaoshaKey.isGoodsOver,""+goodsId,true);
    }
    private boolean getGoodOver(long goodsId) {
        return redisService.exists(MiaoshaKey.isGoodsOver,""+goodsId);
    }
    @Transactional
    public OrderInfo miaosha(MiaoshaUser user, GoodsVo goods){
        boolean success=goodsService.reduceStock(goods);
        if(success)
        return orderService.createOrder(user,goods);
        else {
            setGoodsOver(goods.getId());
            return null;
        }
    }


    public long getMiaoshaResult(Long userId, long goodsId) {
        MiaoshaOrder miaoshaOrder=orderService.getMiaoshaOrderByUserIdGoodsId(userId,goodsId);
        if(miaoshaOrder!=null){
            return miaoshaOrder.getOrderId();
        }else{
            boolean isOver=getGoodOver(goodsId);
            if(isOver) return -1;
            else return 0;
        }

    }


    public boolean checkPath(MiaoshaUser user, long goodsId, String path) {
        if(user==null||path==null)
            return false;
        String pathOld=redisService.get(MiaoshaKey.getMiaoshaPath,""+user.getId()+"_"+goodsId,String.class);
        return path.equals(pathOld);
    }

    public String createMiaoshaPath(MiaoshaUser user, long goodsId) {
        if (user==null|goodsId<0) return null;
        String str= MD5Util.md5(UUIDUtil.uuid()+"123456");
        redisService.set(MiaoshaKey.getMiaoshaPath,""+user.getId()+"_"+goodsId,str);
        return str;
    }

    public BufferedImage createVerifyCode(MiaoshaUser user,long goodsId){
        if(user==null||goodsId<0) return null;
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 20));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        redisService.set(MiaoshaKey.getMiaoshaVerifyCode, user.getId()+","+goodsId, rnd);
        //输出图片
        return image;
    }
    private static char[]op=new char[]{'+','-','*'};
    public String generateVerifyCode(Random random){
        int num1=random.nextInt(10);
        int num2=random.nextInt(10);
        int num3=random.nextInt(10);
        char op1=op[random.nextInt(3)];
        char op2=op[random.nextInt(3)];
        String exp=""+num1+op1+num2+op2+num3;
        return exp;
    }
    public static int calc(String exp){
        try {
            ScriptEngineManager scriptEngineManager=new ScriptEngineManager();
            ScriptEngine engine=scriptEngineManager.getEngineByName("JavaScript");
            return (int) engine.eval(exp);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    public boolean checkVerifyCode(MiaoshaUser user,long goodsId,int verifyCode){
        if(user==null||goodsId<0) return false;
        Integer verifyCodeOld=redisService.get(MiaoshaKey.getMiaoshaVerifyCode,user.getId()+","+goodsId,Integer.class);
        if(verifyCodeOld==null||verifyCodeOld-verifyCode!=0) return false;
        redisService.delete(MiaoshaKey.getMiaoshaVerifyCode,user.getId()+","+goodsId);
        return true;
    }
}
